// src/routes/index.js
const express = require('express');
const jwt = require('jsonwebtoken');
const config = require('../config');
const authController = require('../controllers/authController');
const messageController = require('../controllers/messageController');
const adminController = require('../controllers/adminController');
const adminAuth = require('../middlewares/adminAuth');

const router = express.Router();

// 认证中间件
const authenticate = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'No token provided' });
  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    req.user = decoded;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

// 认证路由
router.post('/auth/register', authController.register);
router.post('/auth/login', authController.login);


// 消息路由（需要认证）
router.post('/message/send', authenticate, messageController.sendMessage);
router.get('/message/history', authenticate, messageController.getMessageHistory);
router.get('/admin/users', adminAuth, adminController.getAllUsers);
router.delete('/admin/users/:userId', adminAuth, adminController.deleteUser);
router.get('/admin/messages', adminAuth, adminController.getAllMessages);

module.exports = router;